package com.ruoyi.webs.utils;

import com.alibaba.fastjson.JSONObject;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping({"/frontcode"})
public class FrontCodeController{
    @RequestMapping({"/getcode"})
    public void getCode(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");


        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, 1);


        Graphics g = image.getGraphics();

        g.setColor(Color.GRAY);

        g.fillRect(0, 0, width, height);


        String checkCode = getCheckCode();

        request.getSession().setAttribute("CHECKCODE_SERVER", checkCode);


        g.setColor(Color.YELLOW);

        g.setFont(new Font("黑体", 1, 24));

        g.drawString(checkCode, 15, 25);


        ImageIO.write(image, "PNG", (OutputStream) response.getOutputStream());
    }


    @ResponseBody
    @RequestMapping({"/checkcode"})
    public JSONObject checkcode(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        try {
            String code = request.getParameter("code");
            String checkcode_server = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
            if (checkcode_server != null) {
                if (checkcode_server.equalsIgnoreCase(code)) {
                    result.put("flag", Boolean.valueOf(true));
                } else {
                    result.put("flag", Boolean.valueOf(false));
                    result.put("msg", "验证码错误！");
                }
            } else {
                result.put("flag", Boolean.valueOf(false));
                result.put("msg", "验证码超时！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {

            int index = r.nextInt(size);

            char c = base.charAt(index);

            sb.append(c);
        }
        return sb.toString();
    }
}